package tyx.study.jsp.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import tyx.study.jsp.dao.IEmpDao;
import tyx.study.jsp.dao.imp.EmpDaoImp;
import tyx.study.jsp.javabean.Emp;
import tyx.study.jsp.mapper.EmpMapper;
import tyx.study.jsp.service.IEmpService;

public class EmpServiceImp implements IEmpService{
	
	private IEmpDao empDao;
	private SqlSession session;
	private EmpMapper mapper;
	public EmpServiceImp() {
		empDao=new EmpDaoImp();
		try {
			InputStream  is = Resources.getResourceAsStream("mybatis-config.xml");
			SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
			session=sessionFactory.openSession(true);
		    mapper= session.getMapper(EmpMapper.class);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	@Override
	public int addEmp(Emp emp) {
		int i=0;
		try {
			if (mapper.selectByEname(emp.getEname())==null) {
				 i= mapper.insert(emp);
				session.commit();
			}
			return i;
			
		} catch (Exception e) {
			session.rollback();
		}
		return 0;
	}
	@Override
	public int getPages(int pageNum) {
		int total= mapper.selectCount();
		int pages=total%pageNum==0?total/pageNum:total/pageNum+1;
		return pages;
	}
	public  List<Emp> allEmps(int page,int pageNum){
		int startPage=(page-1)*pageNum;
		Map<String, Integer> pages=new HashMap<String, Integer>();
		pages.put("startPage", startPage);
		pages.put("pageNum", pageNum);
		return mapper.selectAll(pages);
	}
	
	
	
	@Override
	public Emp findByEno(Integer eno) {
		// TODO Auto-generated method stub
		return mapper.selectByEno(eno);
	}
	@Override
	public int modifyEmp(Emp emp) {
		
		return mapper.updateEmp(emp);
	}
	@Override
	public int removeEmp(Integer eno) {
		// TODO Auto-generated method stub
		return mapper.deleteEmp(eno);
	}
	
	

}
